package com.atguigu.spzx.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.common.util.AuthContextUtil;
import com.atguigu.spzx.manager.constant.CacheConstant;
import com.atguigu.spzx.manager.mapper.SysUserMapper;
import com.atguigu.spzx.manager.service.SysUserService;
import com.atguigu.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.model.dto.system.SysUserDto;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.system.LoginVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

// 分层注解：
// @Controller   @Service    @Repository     @Component

@Service
@Transactional
public class SysUserServiceImpl implements SysUserService { // ctrl + alt + b       ctrl + i       ctrl + o

    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    //@Autowired
    //StringRedisTemplate stringRedisTemplate;

    @Override
    public LoginVo login(LoginDto loginDto) {
        
        //0.校验验证码
        String inputCode = loginDto.getCaptcha();
        String redisCode = redisTemplate.opsForValue().get(CacheConstant.USER_LOGIN_VALIDATECODE_PREFIX + loginDto.getCodeKey());
        if(!StringUtils.hasText(redisCode) || !StrUtil.equals(inputCode,redisCode)){
            throw new GuiguException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

        // 验证通过删除redis中的验证码
        redisTemplate.delete(CacheConstant.USER_LOGIN_VALIDATECODE_PREFIX + loginDto.getCodeKey()) ;

        //1.根据用户名称查询用户对象
        SysUser sysUser = sysUserMapper.selectSysUserByUsername(loginDto.getUserName());
        if(sysUser == null){
            //throw new RuntimeException("用户名称不正确");
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }

        //2.验证密码
        if(!sysUser.getPassword().equalsIgnoreCase(DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes()))){
            //throw new RuntimeException("密码不正确");
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }

        //3.生成令牌
        String token = UUID.randomUUID().toString().replace("-","");
        sysUser.setPassword(null); //密码擦除再保存进redis中。
        redisTemplate.opsForValue().set(CacheConstant.USER_LOGIN_PREFIX+token, JSON.toJSONString(sysUser),30, TimeUnit.MINUTES);

        //4.封装数据
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setRefresh_token("");

        //5.返回数据
        return loginVo;
    }

    //无需自己通过redis获取数据，因为拦截器将redis数据获取后绑定到线程上了，从线程上获取就可以了。
//    @Override
//    public SysUser getUserInfo(String token) {
//        String sysUserJsonStr = redisTemplate.opsForValue().get(CacheConstant.USER_LOGIN_PREFIX+token);
//        SysUser sysUser = JSON.parseObject(sysUserJsonStr,SysUser.class);
//        sysUser.setPassword(null); //密码擦除
//        return sysUser;
//    }


    @Override
    public SysUser getUserInfo(String token) {
        return AuthContextUtil.get();
    }


    @Override
    public void logout(String token) {
        redisTemplate.delete(CacheConstant.USER_LOGIN_PREFIX+token);
    }


    @Override
    public PageInfo<SysUser> findByPage(Integer pageNum, Integer pageSize, SysUserDto sysUserDto) {
        //1.开启分页功能
        PageHelper.startPage(pageNum,pageSize); //原理：将数据通过ThreadLocal,与当前线程进行绑定。

        //2.数据查询
        List<SysUser> list =  sysUserMapper.findByPage(sysUserDto);  //  返回对象其实就是线程绑定Page对象    Page extends ArrayList

        //3.封装数据返回结果
        PageInfo<SysUser> pageInfo = new PageInfo<>(list); //默认导航页数量8
        return pageInfo;
    }

    @Override
    public void save(SysUser sysUser) {
        sysUser.setPassword(DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes()));
        sysUser.setStatus(1); //状态（1：正常 0：停用）
        sysUserMapper.insert(sysUser);
    }

    @Override
    public SysUser getById(Long id) {
        return sysUserMapper.getById(id);
    }

    @Override
    public void update(SysUser sysUser) {
        sysUserMapper.update(sysUser);
    }

    @Override
    public void deleteById(Long id) {
        sysUserMapper.deleteById(id);
    }

}
